#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#include <pthread.h>

pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;
int flag = 1;

void prepare() {
	printf("preparing locks...\n");
	pthread_mutex_lock(&lock1);
	pthread_mutex_lock(&lock2);
}

void parent() {	
	printf("parent unlocking locks...\n");
	pthread_mutex_unlock(&lock1);
	pthread_mutex_unlock(&lock2);
}

void child() {	
	printf("child unlocking locks...\n");
	pthread_mutex_unlock(&lock1);
	pthread_mutex_unlock(&lock2);
}

void* thr_fn(void* arg) {
	printf("thread started\n");
	while (flag) {
		sleep(1);
		printf("--> %x\n", pthread_self());
	}
	return NULL;
}

int main() {
	int err;
	pid_t pid;
	pthread_t tid;

	if ((err=pthread_atfork(prepare, parent, child)) != 0) {
		printf("install fork handler error\n");
		return -1;
	}

	pthread_create(&tid, NULL, thr_fn, NULL);
	sleep(2);

	printf("about to fork\n");
	if ((pid=fork()) < 0) {
		printf("error fork\n");
		return -1;
	}
	else if (pid == 0) {
		printf("child process\n");
		sleep(10);
		flag = 0;
	}
	else {
		printf("parent process\n");
	}
	return 0;
}